package com.azdebugit.apache.beanutils;

import com.alibaba.fastjson.JSON;
import lombok.Data;
import org.junit.Test;
import org.springframework.beans.BeanUtils;

import java.util.Arrays;
import java.util.List;

/**
 * @author
 * @date 2019/10/26
 */
public class BeanUtil {
//    @Test
    public static void main(String[] args) {
        Bean2 bean2 = new Bean2();
        bean2.setIntField(1);
        bean2.setStrField("str");
        bean2.setObjField("obj");
        bean2.setListIntegerField(Arrays.asList("1", "2assdsdsf", "3"));
        bean2.setObjField1("1");
        Bean1 bean1 = new Bean1();

        //属性中有元素不满足目标属性时依旧赋值成功Bean1.listIntegerField），未对能强转成功的属性做赋值处理(Bean1.objField1)
        BeanUtils.copyProperties(bean2, bean1);

        System.out.println("bean2:\t" + bean2);
        System.out.println("bean1:\t" + bean1);
        System.out.println("bean1.getListIntegerField:\t" + bean1.getListIntegerField().get(0));//调用到具体异常元素再抛出异常

        System.out.println("--------------------分割线--------------------");

        Bean1 bean11 = new Bean1();
        bean11.setIntField(1);
        bean11.setStrField("str");
        bean11.setObjField("obj");
        bean11.setListIntegerField(Arrays.asList(1, 2, 3));
        bean11.setObjField1(1);
        Bean2 bean21 = new Bean2();

        //Bean2.objField1 类型大于Bean1.objField1类型，赋值成功
        BeanUtils.copyProperties(bean11, bean21);

        System.out.println("bean11:\t" + bean11);
        System.out.println("bean21:\t" + bean21);
        System.out.println("bean21.getListIntegerField:\t" + bean21.getListIntegerField());

    }

//    @Test
    public void optimizeCopyProperties() {
        Bean2 bean2 = new Bean2();
        bean2.setIntField(1);
        bean2.setStrField("str");
        bean2.setObjField("obj");
//        bean2.setListIntegerField(Arrays.asList("1assdsdsf","2","3"));
        bean2.setListIntegerField(Arrays.asList("1", "2", "3"));
        bean2.setObjField1("1");

        //借助json工具类，底层以字符串实现强转。对能强转成功的属性做赋值并赋值成功，若同名属性值强转赋值失败则抛出异常
        Bean1 bean1 = JSON.parseObject(JSON.toJSONBytes(bean2), Bean1.class);

        System.out.println("bean2:\t" + bean2);
        System.out.println("bean1:\t" + bean1);
        System.out.println("bean1.getListIntegerField:\t" + bean1.getListIntegerField());


    }

    @Data
    public static class Bean1 {
        private int intField;
        private String strField;
        private Object objField;
        private Integer objField1;
        private List<Integer> listIntegerField;
    }

    @Data
    public static class Bean2 {
        private int intField;
        private String strField;
        private Object objField;
        private Object objField1;
        private List<String> listIntegerField;
    }
}